package org.xukai.common.concurrent.lock020;

import java.util.HashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by Administrator on 2016/08/24.
 */
public class WriteReadLock {

    public Object getData(String key){
        ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
        rw.readLock().lock();//在读前先上读锁
        HashMap<Object, Object> map = new HashMap<>();
        Object result = null;
        try{
            result = map.get(key);
            //这个if比较关键，它避免了多余的几次对数据哭的读取
            if(result==null){
                //如果内存中没有所要数据
                rw.readLock().unlock();
                rw.writeLock().lock();
                if(result==null){
                    try{
                        //我们用这个代替对数据库访问得到数据的步骤
                        result = "new";
                    }finally{
                        rw.writeLock().unlock();
                    }
                    rw.readLock().lock();
                }
            }
        }finally{
            rw.readLock().unlock();
        }
        return result;

    }
}
